import logging
import json
import requests

from .config import Config

class ConfigServer(object):
    def __init__(self):
        # 0距离模式     1按区块派单
        self.block_based_algo_flag = 0
        # 关联区块
        self.related_blocks_list = []
        # 预约单提前派
        self.predict_order_lead_duration = 25*60
        # 骑手等单时间
        self.rider_wait_time = 300

        # 闲时定义
        self.free_time_durations = []

        # 压力阈值百分比 默认60
        self.pressure_percent = 60

    @classmethod
    def get_config_server_info(cls, shop_id):
        config_server_obj = ConfigServer()

        url = Config.config_server_api.replace("DATA_ID", "or-algo-dispatch-2-"+shop_id.lower())
        resp = requests.get(url)
        if resp is None or len(resp.json()) == 0 or int(resp.json()["code"]) != 200000 or resp.json()["result"] is None:
            logging.info(f"http获取门店{shop_id}信息失败。{resp}")
            return config_server_obj

        if len(resp.json()["result"]) == 0:
            return config_server_obj

        result_str = resp.json()["result"]

        result_json = json.loads(result_str)
        if "riderWaitTime" in result_json:
            config_server_obj.rider_wait_time = result_json["riderWaitTime"]

        if "blockBasedAlgoFlag" in result_json:
            config_server_obj.block_based_algo_flag = result_json["blockBasedAlgoFlag"]

        if "freeTimeDurations" in result_json:
            config_server_obj.free_time_durations = result_json["freeTimeDurations"]

        if "relatedBlocks" in result_json:
            config_server_obj.related_blocks_list = result_json["relatedBlocks"]

        if "pressurePercent" in result_json:
            config_server_obj.pressure_percent = result_json["pressurePercent"]

        if "predictOrderLeadDuration" in result_json:
            config_server_obj.predict_order_lead_duration = result_json["predictOrderLeadDuration"]

        return config_server_obj
